package com.yfqy.app.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.UUID;

@Component
public class TraceIdFilter extends OncePerRequestFilter {

    private static final String TRACE_ID = "traceId";
    private static final String SPAN_ID = "spanId";
    private static final String HEADER_TRACE_ID = "X-Trace-Id";

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {

        try {
            // 从请求头获取或生成新的traceId
            String traceId = request.getHeader(HEADER_TRACE_ID);
            if (traceId == null || traceId.isEmpty()) {
                traceId = UUID.randomUUID().toString().replace("-", "");
            }

            // 生成spanId
            String spanId = UUID.randomUUID().toString().replace("-", "").substring(0, 8);

            // 放入MDC
            MDC.put(TRACE_ID, traceId);
            MDC.put(SPAN_ID, spanId);

            // 设置响应头，便于前端追踪
            response.addHeader(HEADER_TRACE_ID, traceId);

            filterChain.doFilter(request, response);
        } finally {
            // 清除MDC
            MDC.remove(TRACE_ID);
            MDC.remove(SPAN_ID);
        }
    }
}
